// pages/healthlife/healthlife.js
Page({
  data: {
    item: 0, // 标签页当前显示页面的序号
    categories: [
      { id: 0, name: '全部资讯' },
      { id: 1, name: '健康科普' },
      { id: 2, name: '养生保健' }
    ],
    activeCategory: 0,
    page: 1,
    pageSize: 6,
    totalPage: 1,
    searchKeyword: '',
    activeTab: 0,
    // 添加弹窗相关数据
    showMoreModal: false,
    currentType: '',
    moreCourses: [],

    basicCourses: [], // 基础课程列表
    advancedCourses: [], // 进阶课程列表

    basicCourses: [
      {
        id: 1,
        img: '/images/ceshi3.jpg',
        title: '基础热身训练',
        teacher: '教练：李明',
        desc: '适合初学者的全身热身课程'
      },
      {
        id: 2,
        img: '/images/ceshi1.jpg',
        title: '拉伸放松',
        teacher: '教练：王芳',
        desc: '运动前后的全身拉伸'
      },
      {
        id: 3,
        img: '/images/ceshi2.jpg',
        title: '核心力量训练',
        teacher: '教练：张伟',
        desc: '提升核心稳定性'
      }
    ],
    advancedCourses: [
      {
        id: 1,
        img: '/images/ceshi2.jpg',
        title: 'KILLER HIIT CARDIO',
        teacher: '教练：Alex',
        desc: '高强度间歇燃脂训练'
      },
      {
        id: 2,
        img: '/images/ceshi1.jpg',
        title: '耐力锻炼',
        teacher: '教练：陈晨',
        desc: '提升有氧耐力'
      },
      {
        id: 3,
        img: '/images/ceshi3.jpg',
        title: '普拉提塑形',
        teacher: '教练：刘婷',
        desc: '改善体态，增强柔韧'
      }
    ],
    recommendList: [], // 当前页的推荐列表
    allRecommendList: [], // 存储所有数据
  },
  onLoad() {
    this.loadArticles();
    this.loadHealthData();
    this.loadCourses(); // 加载课程数据
  },
  onTabChange(e) {
    const idx = Number(e.currentTarget.dataset.idx);
    this.setData({
      activeTab: idx,
      page: 1
    }, this.loadHealthData);
  },
  updateRecommendList() {
    const { activeTab, recommendData, page, pageSize } = this.data;
    const allList = recommendData[activeTab] || [];
    const totalPage = Math.ceil(allList.length / pageSize) || 1;
    const start = (page - 1) * pageSize;
    const end = start + pageSize;
    this.setData({
      recommendList: allList.slice(start, end),
      totalPage
    });
  },
  onPrevPage() {
    if (this.data.page > 1) {
      this.setData({
        page: this.data.page - 1
      }, this.updateRecommendList);
    }
  },
  onNextPage() {
    if (this.data.page < this.data.totalPage) {
      this.setData({
        page: this.data.page + 1
      }, this.updateRecommendList);
    }
  },
  onRecommendPrevPage() {
    if (this.data.page > 1) {
      this.setData({
        page: this.data.page - 1
      }, () => {
        const start = (this.data.page - 1) * this.data.pageSize;
        const end = start + this.data.pageSize;
        this.setData({
          recommendList: this.data.allRecommendList.slice(start, end)
        });
      });
    }
  },
  onRecommendNextPage() {
    if (this.data.page < this.data.totalPage) {
      this.setData({
        page: this.data.page + 1
      }, () => {
        const start = (this.data.page - 1) * this.data.pageSize;
        const end = start + this.data.pageSize;
        this.setData({
          recommendList: this.data.allRecommendList.slice(start, end)
        });
      });
    }
  },
  // 顶部标签的点击函数
  changeItem(e) {
    const idx = Number(e.currentTarget.dataset.item);
    this.setData({
      item: idx
    }, () => {
      if (idx === 0) {
        this.loadArticles();
      }
    });
  },
  // 滑块Swiper组件的滑动监听函数
  changeTab(e) {
    const idx = e.detail.current;
    this.setData({
      item: idx
    }, () => {
      if (idx === 0) {
        this.loadArticles();
      }
    });
  },
  onSwiperChange(e) {
    this.setData({
      item: e.detail.current
    });
  },
   // 分类切换
   onCategoryTap(e) {
    const idx = e.currentTarget.dataset.idx;
    this.setData({
      activeCategory: idx,
      page: 1,
      searchKeyword: ''
    }, this.loadArticles);
  },

  // 搜索
  onSearchInput(e) {
    this.setData({
      searchKeyword: e.detail.value
    });
  },
  onSearch() {
    this.setData({
      page: 1
    }, this.loadArticles);
  },

  // 分页
  onPrevPage() {
    if (this.data.page > 1) {
      this.setData({
        page: this.data.page - 1
      }, this.loadArticles);
    }
  },
  onNextPage() {
    if (this.data.page < this.data.totalPage) {
      this.setData({
        page: this.data.page + 1
      }, this.loadArticles);
    }
  },

  // 加载文章列表
  loadArticles() {
    const { activeCategory, page, pageSize, searchKeyword } = this.data;
    let url = 'http://localhost:8080/news';
    
    // 如果有分类，添加type参数
    if (activeCategory !== 0) {
      url += `/type?type=${activeCategory}`;
    }
    wx.request({
      url: url,
      method: 'GET',
      success: (res) => {
        if (res.data && res.data.data) {
          let articles = res.data.data;
          
          // 如果有搜索关键词，进行过滤
          if (searchKeyword) {
            articles = articles.filter(item =>
              item.title.includes(searchKeyword) ||
              item.content.includes(searchKeyword)
            );
          }

          // 分页处理
          const totalPage = Math.ceil(articles.length / pageSize) || 1;
          const start = (page - 1) * pageSize;
          const end = start + pageSize;
          
          this.setData({
            newsList: articles.slice(start, end).map(item => ({
              id: item.id,
              img: item.coverImg || '/images/default.jpg',
              title: item.title,
              desc: item.content ? item.content.substring(0, 30) + '...' : '',
              date: item.createTime || new Date().toLocaleDateString(),
              category: item.type
            })),
            totalPage
          });
        }
      },
      fail: (error) => {
        console.error('获取新闻列表失败：', error);
        wx.showToast({
          title: '获取新闻列表失败',
          icon: 'none'
        });
      }
    });
  },

  onNewsTap(e) {
    const id = e.currentTarget.dataset.id;
    // 判断当前tab栏
    if (this.data.item === 1) {
      wx.navigateTo({
        url: `/pages/healthlife/festivaldetails/festivaldetails?id=${id}`
      });
    } else {
      wx.navigateTo({
        url: `/pages/healthlife/healthdetails/healthdetails?id=${id}`
      });
    }
  },
  // 加载养生数据
  loadHealthData() {
    const type = this.data.activeTab; // 0:食疗养生, 1:自我保健, 2:节气养生
    let url = 'http://localhost:8080/articles';
    
    if (type === 0 || type === 1 || type === 2) {
      url += `/type?type=${type}`;
    }

    wx.request({
      url: url,
      method: 'GET',
      success: (res) => {
        if (res.data && res.data.data) {
          const allArticles = res.data.data.map(item => ({
            id: item.id,
            img: item.coverImg || '/images/default.jpg',
            title: item.title,
            desc: item.content ? item.content.substring(0, 30) + '...' : '',
            author: item.authorNickname || '佚名',
            view: item.view || 0
          }));

          // 计算总页数
          const totalPage = Math.ceil(allArticles.length / this.data.pageSize) || 1;
          
          // 获取当前页的数据
          const start = (this.data.page - 1) * this.data.pageSize;
          const end = start + this.data.pageSize;
          const currentPageArticles = allArticles.slice(start, end);

          this.setData({
            allRecommendList: allArticles,
            recommendList: currentPageArticles,
            totalPage: totalPage
          });
        }
      },
      fail: (err) => {
        console.error('获取养生数据失败：', err);
        wx.showToast({
          title: '获取数据失败',
          icon: 'none'
        });
      }
    });
  },
  goToCourseDetails(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/healthlife/coursedetails/coursedetails?id=${id}`
    });
  },
  goToCourseList(e) {
    const type = e.currentTarget.dataset.type;
    wx.navigateTo({
      url: `/pages/healthlife/courselist/courselist?tab=${type === 'basic' ? 0 : 1}`
    });
  },
  // 加载课程数据
  loadCourses() {
    // 获取基础课程（level=0）
    wx.request({
      url: 'http://localhost:8080/courses/level/0',
      method: 'GET',
      success: (res) => {
        if (res.data && res.data.data) {
          const basicCourses = res.data.data.slice(0, 4).map(course => ({
            id: course.id,
            img: course.coverImg || '/images/default.jpg',
            title: course.title,
            teacher: `教练：${course.authorNickname || '未知'}`,
            desc: course.introduce || '暂无描述'
          }));
          this.setData({ basicCourses });
        }
      },
      fail: (error) => {
        console.error('获取基础课程失败：', error);
        wx.showToast({
          title: '获取基础课程失败',
          icon: 'none'
        });
      }
    });

    // 获取进阶课程（level=1）
    wx.request({
      url: 'http://localhost:8080/courses/level/1',
      method: 'GET',
      success: (res) => {
        if (res.data && res.data.data) {
          const advancedCourses = res.data.data.slice(0, 4).map(course => ({
            id: course.id,
            img: course.coverImg || '/images/default.jpg',
            title: course.title,
            teacher: `教练：${course.authorNickname || '未知'}`,
            desc: course.introduce || '暂无描述'
          }));
          this.setData({ advancedCourses });
        }
      },
      fail: (error) => {
        console.error('获取进阶课程失败：', error);
        wx.showToast({
          title: '获取进阶课程失败',
          icon: 'none'
        });
      }
    });
  },
})
